package com.katesoft.scale4j.rttp.jmx;

import org.hibernate.jmx.StatisticsService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.jmx.export.MBeanExporter;

import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;

import static com.katesoft.scale4j.rttp.jmx.IRttpSupportMBean.OBJ_RTTP_ATOMIKOS_STATISTIC;
import static com.katesoft.scale4j.rttp.jmx.IRttpSupportMBean.OBJ_RTTP_HIBERNATE_STATISTIC;

/**
 * @author kate2007
 */
public class RttpExporter extends MBeanExporter implements ApplicationContextAware {
   private ApplicationContext applicationContext;
   private StatisticsService hibernateStatisticsService;
   private Collection<String> excludeNames = new LinkedHashSet<String>();
   private Map<String, Object> beans = new LinkedHashMap<String, Object>();

   @Override
   public void afterPropertiesSet() {
      beans.put(OBJ_RTTP_HIBERNATE_STATISTIC, hibernateStatisticsService);
      excludeNames.add("jvmcluster.hibernate.statistic.bean");
      //
      if (applicationContext.containsBeanDefinition("jmx.transaction.service")) {
         beans.put(OBJ_RTTP_ATOMIKOS_STATISTIC,
                  applicationContext.getBean("jmx.transaction.service"));
         excludeNames.add("jmx.transaction.service");
      }
      super.setExcludedBeans(excludeNames.toArray(new String[excludeNames.size()]));
      super.setBeans(beans);
      super.afterPropertiesSet();
   }

   @Override
   public void setBeans(Map<String, Object> beans) {
      this.beans.putAll(beans);
   }

   @Override
   public void setExcludedBeans(String[] excludedBeans) {
      this.excludeNames.addAll(Arrays.asList(excludedBeans));
   }

   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      this.applicationContext = applicationContext;
   }

   @Required
   public void setHibernateStatisticsService(StatisticsService hibernateStatisticsService) {
      this.hibernateStatisticsService = hibernateStatisticsService;
   }
}
